<?php

namespace app\admin\controller\statistics;

use app\admin\library\Auth;
use app\admin\model\develop\Acuisitionscheme;
use app\admin\model\entrepot\Receiving;
use app\common\controller\Backend;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\statistics\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\statistics\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看订单列表
     * @return string|\think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @author lhq
     */
    public function index()
    {
        up_order_schedule(107);
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'order_no', 'schedule', 'createtime', 'updatetime', 'status']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加订单
     * @return string
     * @throws \think\Exception
     * @author lhq
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    //判断是否存在相同的订单号
                    if ($this->model->where('order_no', 'eq', $params['order_no'])->value('id')) $this->error('订单号已存在！');
                    $result = $this->model->allowField(true)->save($params);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
//        $this->view->assign('row',$row);
        return $this->view->fetch();
    }

    /**
     * 删除订单
     * @param $ids
     * @return void
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author lhq
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            //判断删除丁订单是否存在收货记录
            foreach ($list as $k => $v) {
                if ($v['schedule'] > 0) {
                    Db::rollback();
                    $this->error(__('已有收货记录无法删除'));
                }
            }

            Db::startTrans();
            try {
                //领料表模型
                $acuisitionschemeModel = new Acuisitionscheme();

                //执行删除操作
                $count = 0;
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    //删除领料方案数据
                    $acuisitionschemeModel->where('order_id', 'eq', $v['id'])->delete();
                    //删除订单明细数据
                    Db::name('order_detail')->where('order_id', 'eq', $v['id'])->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 添加订单明细
     * @param $ids
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author lhq
     */
    public function add_detail($ids = '')
    {
        if ($this->request->isPost()) {
            $orderDetailModel = new \app\admin\model\statistics\Orderdetail();
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }

                //判断当前订单下是否有相同商标印字和色号的明细
                $checkWhere['order_id'] = $params['order_id'];
                $checkWhere['trademark_printing'] = $params['trademark_printing'];
                $checkWhere['colour_id'] = $params['colour_id'];
                $issetDetail = Db::name('order_detail')->where($checkWhere)->count();
                if ($issetDetail > 0) {
                    Db::rollback();
                    $this->error('当前订单下已经存在相同数据');
                }

                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($orderDetailModel));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $orderDetailModel->validateFailException(true)->validate($validate);
                    }

                    //执行添加
                    $result = $orderDetailModel->allowField(true)->save($params);
                    if (!$result) {
                        Db::rollback();
                        $this->error('添加失败');
                    }
                    $order_detail_id = $orderDetailModel->getLastInsID();

                    //查询物料方案
                    $materialplan = new \app\admin\model\statistics\Materialplan;
                    $materialplan_where['trademark_printing'] = $params['trademark_printing'];
                    $materialplan_where['colour_id'] = $params['colour_id'];
                    $materialplanArr = collection($materialplan->where($materialplan_where)->order('id', 'desc')->select())->toArray();
                    if (count($materialplanArr) > 0) {//存在物料方案
                        //获取主方案数据
                        $materialplanData = [];
                        foreach ($materialplanArr as $k => $v) {
                            if ($v['attribute'] == 1) {
                                $materialplanData = $v;
                                break;
                            }
                        }
                        if (!$materialplanData) {
                            $materialplanData = $materialplanArr[count($materialplanArr) - 1];
                        }

                        //领料方案
                        $acquisitionscheme = new Acuisitionscheme();
                        $acquisitionscheme_insert['order_id'] = $params['order_id'];
                        $acquisitionscheme_insert['order_detail_id'] = $order_detail_id;
                        $acquisitionscheme_insert['colour_id'] = $params['colour_id'];
                        $acquisitionscheme_insert['material_plan_id'] = $materialplanData['id'];

                        if ($materialplanData['status'] == 1) {
                            //如果领料方案状态为已处理，生成领料方案
                            if (!$acquisitionscheme->save($acquisitionscheme_insert)) {
                                Db::rollback();
                                $this->error('添加失败1');
                            }

                            $order_detail_update['status'] = 1;
                        } else {
                            //如果状态等于0、2、3
                            if ($materialplanData['status'] == 0) {
                                $order_detail_update['status'] = 0;
                            } else {
                                //获取物料方案审核表是否存在已经审核通过记录
                                $materialPlanAuditModel = new \app\admin\model\statistics\Materialplanaudit();
                                $w['pid'] = $materialplanData['id'];
                                $w['status'] = 1;
                                $isHadAuditData = $materialPlanAuditModel->where($w)->count();

                                if ($isHadAuditData == 0) {
                                    $order_detail_update['status'] = 0;
                                } else {
                                    //如果存在审核通过的记录，生成领料方案
                                    if (!$acquisitionscheme->save($acquisitionscheme_insert)) {
                                        Db::rollback();
                                        $this->error('添加失败2');
                                    }
                                    $order_detail_update['status'] = 1;
                                }
                            }
                        }

                        $where['id'] = $order_detail_id;
                        if ($order_detail_update['status'] == 1 && !$orderDetailModel::where($where)->update($order_detail_update)) {
                            Db::rollback();
                            $this->error('添加失败3');
                        }

                    } else {//不存在，添加物料方案
                        $materialplan_insert['trademark_printing'] = $params['trademark_printing'];
                        $materialplan_insert['abbreviation'] = $params['abbreviation'];
                        $materialplan_insert['colour_id'] = $params['colour_id'];
                        $materialplan_re = $materialplan->insert($materialplan_insert);
                    }

                    //判断是否存在商品工序
                    $processWhere['trademark_printing'] = $params['trademark_printing'];
                    $processArr = Db::name('process')->where($processWhere)->select();
                    if ($processArr && is_array($processArr)) {
                        foreach ($processArr as $key => $val) {
                            $colourArr = explode(',', $val['colour_ids']);
                            if (in_array($params['colour_id'], $colourArr)) {
                                $processList = explode(',', $val['process_attribute_ids']);
                                $process_detail = [];
                                foreach ($processList as $k2 => $v2) {
                                    $new_data['process_attribute'] = $v2;
                                    $new_data['quantity'] = 0; //工序收取量
                                    $new_data['schedule'] = 0; //工序进度=工序累计收取量/订单总数*100
                                    $new_data['weights'] = 0; //工序权重 = 工序收取量/色号收取总数*工序进度/100
                                    $process_detail[] = $new_data;
                                }
                                $upOrderDetail['process_detail'] = json_encode($process_detail, JSON_UNESCAPED_UNICODE);
                                if (!Db::name('order_detail')->where('id', 'eq', $order_detail_id)->update($upOrderDetail)) {
                                    Db::rollback();
                                    $this->error('添加失败4');
                                }
                                break;
                            }
                        }
                        //更细订单进度
                        up_order_schedule($ids);

                    }
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                Db::commit();
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assign('order_id', $ids);
        return $this->view->fetch();
    }

    public function show_detail($ids = '')
    {

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            p($ids);
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

//            p($this->buildparams());
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['order', 'colour'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'trademark_printing', 'abbreviation', 'quantity', 'cumulative_quantity', 'createtime', 'updatetime', 'status', 'process_detail']);
                $row->visible(['order']);
                $row->getRelation('order')->visible(['order_no']);
                $row->visible(['colour']);
                $row->getRelation('colour')->visible(['name']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * @return void
     * by lhq
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }

            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                $row = [];
                $temp = array_combine($fields, $values);
                foreach ($temp as $k => $v) {
                    if (isset($fieldArr[$k]) && $k !== '') {
                        if (!Db::name('order')->where('order_no', 'eq', $v)->count()) {
                            $row[$fieldArr[$k]] = $v;
                        }
                    }
                }
                if ($row) {
                    $insert[] = $row;
                }
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }

        try {
            //是否包含admin_id字段
            $has_admin_id = false;
            foreach ($fieldArr as $name => $key) {
                if ($key == 'admin_id') {
                    $has_admin_id = true;
                    break;
                }
            }
            if ($has_admin_id) {
                $auth = Auth::instance();
                foreach ($insert as &$val) {
                    if (!isset($val['admin_id']) || empty($val['admin_id'])) {
                        $val['admin_id'] = $auth->isLogin() ? $auth->id : 0;
                    }
                }
            }
            p($insert);
            $this->model->saveAll($insert);
        } catch (PDOException $exception) {
            $msg = $exception->getMessage();
            if (preg_match("/.+Integrity constraint violation: 1062 Duplicate entry '(.+)' for key '(.+)'/is", $msg, $matches)) {
                $msg = "导入失败，包含【{$matches[1]}】的记录已存在";
            };
            $this->error($msg);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success();
    }
}
